package cn.tedu.sp11zuul.filter;

import cn.tdeu.sp01.web.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.sun.scenario.effect.FilterContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    /**
     * 设置过滤器的类型
     *
     * @return
     */
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 过滤器添加的位置顺序号
     * @return
     */
    @Override
    public int filterOrder() {
        return 6;
    }

    /**
     * 判断针对当前请求,是否要执行过滤代码
     * @return
     */
    @Override
    public boolean shouldFilter() {
        /*
        获取用户调用的后台服务id
        2.检查服务id 如果服务id是"item-server" 返回true 否则返回false
         */
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId = (String) ctx.get(FilterConstants.SERVICE_ID_KEY);
        return "item-service".equalsIgnoreCase(serviceId);
    }

    /**
     * 过滤代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        /*
        1.接收参数 token参数
        2.如果没有token 阻止继续调用,直接返回登录提示
         */
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String to = request.getParameter("token");
        if (StringUtils.isBlank(to)){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);

            ctx.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            ctx.setResponseBody(JsonResult.err().code(401).msg("not login! 未登录").toString());
        }
        return null;  //返回值目前没有任何作用
    }
}
